/*
 * $Id: MyException.C,v 1.2 1999/02/24 08:57:55 dms Exp $
 *
 *
 */

#include <stdio.h>
#include <syslog.h>
#include <signal.h>
#include <stdarg.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <errno.h>

extern int errno;

#include <popen/MyException.h>

char progname[64];

MyException::MyException(char * tag, char *format, ... )
  {
     va_list ap;
     va_start(ap, format);

     fire(_message, format, ap);

     va_end(ap);
  }

void MyException::fire(char * tag, char *format, va_list ap )
  {
     /*add errno if need*/
      char *s;
      if ( (s = strstr(format,"%m")) )
         { char tmp[MAX_EX_MESSAGE];
           strncpy(tmp,format,s-format); tmp[s-format] = 0;
           strcat(tmp, strerror(errno));
           if (*(s+2)) strcat(tmp,s+2);
           vsprintf(_message, tmp, ap);
         }
         else
          { vsprintf(_message, format, ap);
          }

     strcpy(_tag, tag);

#ifdef SYSLOG_EXCEPTION
     openlog( _tag, LOG_PID, LOG_ERR);
#endif
  }


void set_sighandler(char *pname)
{
  strcpy(progname, pname);

  // openlog(progname,LOG_PID | LOG_PERROR, LOG_ERR);
  openlog(progname,LOG_PID, LOG_ERR);

 // signal(SIGINT,  sighandler);
  signal(SIGQUIT, __sighandler);
  signal(SIGILL,  __sighandler);
  signal(SIGTRAP, __sighandler);
  signal(SIGBUS,  __sighandler);
  signal(SIGSEGV, __sighandler);
}

void __sighandler(int sig)
{
 char *sname= "UNLISTED";

 switch(sig)
 {
  case SIGINT:  sname="SIGINT";  break;
  case SIGQUIT: sname="SIGQUIT"; break;
  case SIGILL:  sname="SIGILL";  break;
  case SIGTRAP: sname="SIGTRAP"; break;
  case SIGABRT: sname="SIGABRT"; break;
  case SIGBUS:  sname="SIGBUS";  break;
  case SIGSEGV: sname="SIGSEGV"; break;
 }

 chdir(TMP_PATH);

#ifdef SYSLOG_EXCEPTION
 syslog(LOG_ERR, "Signal: %s (%d) reached. Exiting with core.\n", sname, sig);
#else
 fprintf(stderr,  "Signal: %s (%d) reached. Exiting with core.\n", sname, sig);
#endif

 abort();
}

